using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RectPositionConstraint:MonoBehaviour {

	[SerializeReference] RectTransform rectTransform;
	[SerializeReference] RectTransform rectTransformCanvas;
	Canvas canvas;

	private void Start() {
		if(rectTransform==null) rectTransform=transform as RectTransform;
		canvas=GetComponentInParent<Canvas>();
		if(canvas&&rectTransformCanvas==null) rectTransformCanvas=canvas.transform as RectTransform;
	}

	private void LateUpdate() {

		Bounds canvasBounds = Utility.GetRectBounds(rectTransformCanvas);
		Bounds selfBounds = Utility.GetRectBounds(rectTransform);

		Vector3 nudge = Vector3.zero;
		if(selfBounds.min.x<canvasBounds.min.x) nudge.x=canvasBounds.min.x-selfBounds.min.x;
		if(selfBounds.min.y<canvasBounds.min.y) nudge.y=canvasBounds.min.y-selfBounds.min.y;
		if(selfBounds.max.x>canvasBounds.max.x) nudge.x=canvasBounds.max.x-selfBounds.max.x;
		if(selfBounds.max.y>canvasBounds.max.y) nudge.y=canvasBounds.max.y-selfBounds.max.y;

		transform.position+=nudge;

	}


}
